using System;
using System.Collections.Generic;
using TTEngine.TTMath;
using Silk.NET.OpenGLES;
namespace TTEngine.Graphics
{
    /// <summary>
    /// 用来执行屏幕裁剪
    /// </summary>
    public class ScreenClipper
    {
        Stack<SizeRect> _stack = new Stack<SizeRect>();

        public ScreenClipper()
        {
        }

        public void Push(SizeRect rect)
        {
            if (_stack.Count > 0)
            {
                // 与栈顶矩形求交
                rect = rect.Intersect(_stack.Peek());
            }
            _stack.Push(rect);
        }

        public void Pop()
        {
            if (_stack.Count > 0)
            {
                _stack.Pop();
            }
        }

        public void Clear()
        {
            _stack.Clear();
        }

        public SizeRect? Peek()
        {
            if (_stack.Count == 0)
                return null;
            return _stack.Peek();
        }

        public int Count => _stack.Count;

        public void ApplyScissor()
        {
            var rect = Peek();
            if (rect != null)
            {
                TTEngine.Runtime.activeGL.Enable(EnableCap.ScissorTest);
                TTEngine.Runtime.activeGL.Scissor(rect.Value.X, rect.Value.Y, (uint)rect.Value.Width, (uint)rect.Value.Height);
            }
            else
            {
                TTEngine.Runtime.activeGL.Disable(EnableCap.ScissorTest);
            }
        }
        public void ClearAndApplyScissor()
        {
            _stack.Clear();
            TTEngine.Runtime.activeGL.Disable(EnableCap.ScissorTest);
        }
    }
}